import { baseURL } from "./config"

const httpInterceptor = {
	invoke(options) {
		// 1. 非http开头需拼接地址
		if (!options.url.startsWith('http')) {
			options.url = baseURL + options.url
		}
		// 2. 请求超时，默认60s
		options.timeout = 10000
		// 3. header中设置token
		options.header = {
			...options.header,
			'content-type': 'application/json',
		}
	}
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', {
	invoke(options) {
		if (!options.url.startsWith('http')) {
			options.url = baseURL + options.url
		}
		options.header = {
			'token': uni.getStorageSync("token")
		}
	}
});


export const http = (options) => {
	return new Promise((resolve, reject) => {
		if (options.tips) {
			uni.showLoading({
				mask: true,
				title: options.tips
			})
		}
		uni.request({
			...options,
			success: (res) => {
				if (options.tips) {
					uni.hideLoading()
				}
				if (res.statusCode.toString().startsWith('2')) {
					if (res.data.code == 500) {
						
						uni.showToast({
							title: res.data.data || res.data.msg,
							icon: "none"
						})
						reject(res.data)
						return
					}
					resolve(res.data)
				} else if (res.statusCode.toString().startsWith('5')) {
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					})
					reject(res.data)
				} else if (res.statusCode == 401) {
					uni.removeStorageSync("token")
					reject(res)
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					})
					reject(res.data)
				}
			},
			fail: (err) => {
				if (options.tips) {
					uni.hideLoading()
				}
				uni.showToast({
					title: "网络错误，请稍后再试",
					icon: "none"
				})
				reject(err)
			}
		})
	})
}
//图片上传
export const uploadImg = (options) => {
	return new Promise((resolve, reject) => {
		let defultOptions = {
			url: baseURL + options.url,
			timeout: options.timeout || 30000,
			filePath: options.data.filePath || "",
			name: options.name || "file",
		};
		uni.showLoading({
			mask: true,
			title: '上传中...'
		})
		uni.uploadFile({
			...defultOptions,
			success: (res) => {
				uni.hideLoading()
				let result = JSON.parse(res.data)
				if (result.code == 200) {
					resolve(result)
				} else {
					uni.showToast({
						title: result.data.msg,
						icon: "none"
					})
					reject(result)
				}
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					title: "网络错误，请稍后再试",
					icon: "none"
				})
				reject(err)
			}
		})

	})
}